let dragSrc, dragSrcTgt, prevTgt, prevRect, lastClickTime;

window.addEventListener("load", function () {
  console.log("event handler loaded");
  initTableEvent();
  initButtonEvent();
  initTxtEvent();
  initCopyDrag();
  initDelDrag();
  initDraw2D();
});

function mouseEnterHandlerForButton(e) {
  if (e.target.nextElementSibling)
    e.target.nextElementSibling.classList.remove("dspNone");
}
function mouseLeaveHandlerForButton(e) {
  if (
    e.target.nextElementSibling &&
    e.target.nextElementSibling.classList.contains("dropdown-content")
  ) {
    let rect = e.target.getBoundingClientRect();
    if (e.x < rect.right) e.target.nextElementSibling.classList.add("dspNone");
  }
}
function mouseEnterHandlerForDropdown(e) {
  e.target.classList.remove("dspNone");
}
function mouseLeaveHandlerForDropdown(e) {
  e.target.classList.add("dspNone");
}
function dragEnterHandler(e) {
  e.target.classList.add("dragenter");
  if (e.target.nextElementSibling)
    e.target.nextElementSibling.classList.remove("dspNone");
}
function dragLeaveHandler(e) {
  e.preventDefault();
  e.target.classList.remove("dragenter");
  if (
    e.target.nextElementSibling &&
    e.target.nextElementSibling.classList.contains("dropdown-content")
  ) {
    let rect = e.target.getBoundingClientRect();
    if (e.x < rect.right) e.target.nextElementSibling.classList.add("dspNone");
  }
  e.stopPropagation();
}
function dragEnterHandlerForDropdown(e) {
  e.preventDefault();
  e.target.closest("div").classList.remove("dspNone");
  prevRect = e.target.closest("div").getBoundingClientRect();
}
function dragLeaveHandlerForDropdown(e) {
  e.preventDefault();
  if (
    e.x < prevRect.left ||
    e.x > prevRect.right ||
    e.y < prevRect.top ||
    e.y > prevRect.bottom
  )
    e.target.closest("div").classList.add("dspNone");
}
function delayedSingleClick(e) {
  clearTimeout(lastClickTime);
  let tb = e.target.closest("table");
  let lb = tb.querySelector("caption>label");
  lastClickTime = setTimeout(() => {
    if (!tb.classList.contains("selected")) {
      lb.classList.add("dspInlineblock");
      tb.classList.add("selected");
    } else {
      lb.classList.remove("dspInlineblock");
      tb.classList.remove("selected");
    }
    updateSelection();
  }, 200);
}
function dblclickHandler(e) {
  clearTimeout(lastClickTime);
  const target = e.target;
  target.contentEditable = "true";
  target.focus();
  if (target.contentEditable === "true") {
    const range = document.createRange();
    range.selectNodeContents(target);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    target.addEventListener("blur", () => {
      target.contentEditable = "false";
    });
  }
}
function switchHandler(e) {
  e.preventDefault();
  try {
    window[e.target.getAttribute("data-func")]((drag = true));
  } catch {
    console.log("switchhandler error");
  }
  dragLeaveHandler(e);
}
function initTableEvent() {
  let tbs = document.querySelectorAll("table");
  for (tb of tbs) addTableEvent(tb);
  tbs = document.querySelector("#matDiv").querySelectorAll("table");
  for (tb of tbs) removeEventListener("click", delayedSingleClick);
}
function addTableEvent(tb) {
  let tbd = tb.querySelector("tbody");
  let cap = tb.querySelector("caption");
  tb.draggable = true;
  tb.addEventListener("dragstart", (e) => {
    dragSrc = e.target.querySelector("tbody").innerText;
    dragSrcTgt = e.target;
  });
  tbd.addEventListener("dblclick", dblclickHandler);
  tb.addEventListener("click", delayedSingleClick);
  cap.addEventListener("dblclick", dblclickHandler);
}
function initButtonEvent() {
  let btns = document
    .querySelector("#menu")
    .querySelectorAll("button.normalButton");
  for (let btn of btns) {
    btn.addEventListener("dragenter", dragEnterHandler);
    btn.addEventListener("dragleave", dragLeaveHandler);
    btn.addEventListener("mouseenter", mouseEnterHandlerForButton);
    btn.addEventListener("mouseleave", mouseLeaveHandlerForButton);
    btn.addEventListener("dragover", (e) => e.preventDefault());
    btn.addEventListener("drop", switchHandler);
  }
  btns = document
    .querySelector("#menu")
    .querySelectorAll("button.dropdownButton");
  for (let btn of btns) {
    btn.addEventListener("dragenter", (e) =>
      e.target.classList.add("dragenter")
    );
    btn.addEventListener("dragleave", (e) =>
      e.target.classList.remove("dragenter")
    );
    btn.addEventListener("dragover", (e) => e.preventDefault());
    btn.addEventListener("drop", switchHandler);
  }
  let dcs = document
    .querySelector("#menu")
    .querySelectorAll("div.dropdown-content");
  for (let dc of dcs) {
    dc.addEventListener("mouseenter", mouseEnterHandlerForDropdown);
    dc.addEventListener("mouseleave", mouseLeaveHandlerForDropdown);
    dc.addEventListener("dragenter", dragEnterHandlerForDropdown);
    dc.addEventListener("dragleave", dragLeaveHandlerForDropdown);
    dc.addEventListener("dragover", (e) => e.preventDefault());
  }
}
function initTxtEvent() {
  let txtars = document.querySelectorAll("textarea");
  for (let txtar of txtars) {
    txtar.addEventListener("dragenter", (e) =>
      e.target.classList.add("dragenter")
    );
    txtar.addEventListener("dragleave", (e) =>
      e.target.classList.remove("dragenter")
    );
    txtar.addEventListener("dragover", (e) => e.preventDefault());
    txtar.addEventListener("drop", (e) => {
      e.preventDefault();
      e.target.value = dragSrc;
      if (e.target.id) {
        M[e.target.id[5]].parseInput(); //i.e. id="input2" -> id[5]=2
        M[e.target.id[5]].fillTable();
      }
      dragLeaveHandler(e);
    });
    txtar.addEventListener("change", (e) => {
      if (e.target.id) {
        M[e.target.id[5]].parseInput();
        M[e.target.id[5]].fillTable();
        e.target.parentNode
          .getElementsByTagName("img")[0]
          .classList.remove("dspInlineblock");
      }
    });
  }
}
function initCopyDrag() {
  let cd = document.querySelector("#dragCopy");
  cd.addEventListener("dragenter", dragEnterHandler);
  cd.addEventListener("dragleave", dragLeaveHandler);
  cd.addEventListener("drop", (e) => {
    document.querySelector("#input0").value = dragSrc;
    M[0].parseInput();
    let result = M[0].copyMat(true);
    result.genTable("copy " + dragSrcTgt.querySelector("caption").innerText);
    dragLeaveHandler(e);
  });
  cd.addEventListener("dragover", (e) => e.preventDefault());
}
function initDelDrag() {
  let dd = document.querySelector("#dragDel");
  dd.addEventListener("dragenter", dragEnterHandler);
  dd.addEventListener("dragleave", dragLeaveHandler);
  dd.addEventListener("drop", (e) => {
    if (dragSrcTgt.hasAttribute("data-fixed"))
      dragSrcTgt.querySelector("tbody").replaceChildren();
    else dragSrcTgt.parentNode.removeChild(dragSrcTgt);
    dragLeaveHandler(e);
  });
  dd.addEventListener("dragover", (e) => e.preventDefault());
}

function initDraw2D() {
  let dr = document.getElementById("idDraw");
  let d = document.getElementById("graphDiv");
  dr.addEventListener("click", () => d.classList.remove("dspNone"));
}
